{% extends "base.html" %}

{% block title %}用户反馈 - 工时工具{% endblock %}

{% block content %}
<div class="max-w-2xl mx-auto py-12 px-4 sm:px-6 lg:px-8">
    <!-- 卡片容器，添加阴影和悬停效果 -->
    <div class="card bg-white rounded-2xl shadow-lg overflow-hidden transition-all duration-300 hover:shadow-xl">
        <!-- 标题区域，添加装饰元素 -->
        <div class="bg-gradient-to-r from-primary/90 to-primary p-6">
            <h2 class="text-2xl font-bold text-white mb-2 flex items-center">
                <i class="fa fa-commenting-o mr-3 animate-pulse-slow"></i>用户反馈
            </h2>
            <p class="text-white/80 text-sm">我们重视您的每一条建议，帮助我们不断改进</p>
        </div>

        <!-- 表单区域 -->
        <div class="p-6 md:p-8">
            <form id="feedbackForm" class="space-y-6">
                <!-- 姓名字段 -->
                <div class="form-group">
                    <label for="name" class="block text-sm font-medium text-gray-700 mb-1 transition-colors duration-200">姓名（选填）</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500 transition-colors duration-200">
                            <i class="fa fa-user"></i>
                        </span>
                        <input
                            type="text"
                            id="name"
                            name="name"
                            class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg input-focus transition-all duration-300 focus:ring-2 focus:ring-primary/20 focus:border-primary"
                            placeholder="请输入您的姓名"
                        >
                        <div class="hidden validation-icon absolute inset-y-0 right-0 flex items-center pr-3"></div>
                    </div>
                </div>

                <!-- 邮箱字段 -->
                <div class="form-group">
                    <label for="email" class="block text-sm font-medium text-gray-700 mb-1 transition-colors duration-200">邮箱（必填）</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500 transition-colors duration-200">
                            <i class="fa fa-envelope"></i>
                        </span>
                        <input
                            type="email"
                            id="email"
                            name="email"
                            class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg input-focus transition-all duration-300 focus:ring-2 focus:ring-primary/20 focus:border-primary"
                            placeholder="请输入您的邮箱，以便我们回复"
                            required
                        >
                        <div class="hidden validation-icon absolute inset-y-0 right-0 flex items-center pr-3"></div>
                    </div>
                    <p class="mt-1 text-xs text-gray-500 hidden error-message"></p>
                </div>

                <!-- 主题字段 -->
                <div class="form-group">
                    <label for="subject" class="block text-sm font-medium text-gray-700 mb-1 transition-colors duration-200">反馈主题（必填）</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 flex items-center pl-3 text-gray-500 transition-colors duration-200">
                            <i class="fa fa-tag"></i>
                        </span>
                        <input
                            type="text"
                            id="subject"
                            name="subject"
                            class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg input-focus transition-all duration-300 focus:ring-2 focus:ring-primary/20 focus:border-primary"
                            placeholder="请简要描述反馈主题"
                            required
                        >
                        <div class="hidden validation-icon absolute inset-y-0 right-0 flex items-center pr-3"></div>
                    </div>
                    <p class="mt-1 text-xs text-gray-500 hidden error-message"></p>
                </div>

                <!-- 内容字段 -->
                <div class="form-group">
                    <label for="content" class="block text-sm font-medium text-gray-700 mb-1 transition-colors duration-200">反馈内容（必填）</label>
                    <div class="relative">
                        <span class="absolute top-3 left-3 text-gray-500 transition-colors duration-200">
                            <i class="fa fa-comment"></i>
                        </span>
                        <textarea
                            id="content"
                            name="content"
                            rows="6"
                            class="w-full pl-10 pr-4 py-3 border border-gray-300 rounded-lg input-focus transition-all duration-300 focus:ring-2 focus:ring-primary/20 focus:border-primary resize-none"
                            placeholder="请详细描述您遇到的问题或建议..."
                            required
                        ></textarea>
                        <div class="hidden validation-icon absolute top-3 right-3"></div>
                        <div class="absolute bottom-3 right-3 text-xs text-gray-500">
                            <span id="charCount">0</span>/500
                        </div>
                    </div>
                    <p class="mt-1 text-xs text-gray-500 hidden error-message"></p>
                </div>

                <!-- 提交按钮 -->
                <div class="flex justify-end pt-2">
                    <button
                        type="submit"
                        class="btn-primary flex items-center px-6 py-3 rounded-lg font-medium shadow-md hover:shadow-lg hover:bg-primary/90 active:scale-98 transition-all duration-300"
                        id="submitBtn"
                    >
                        <i class="fa fa-paper-plane mr-2"></i>提交反馈
                    </button>
                </div>
            </form>

            <!-- 反馈结果提示 - 添加动画效果 -->
            <div id="feedbackResult" class="mt-6 hidden transform transition-all duration-500 opacity-0 translate-y-2"></div>

            <!-- 倒计时提示 -->
            <div id="countdown提示" class="mt-4 text-sm text-gray-500 hidden transform transition-all duration-300 opacity-0">
                您可以在 <span id="countdown" class="font-medium text-primary"></span> 后再次提交反馈
            </div>
        </div>
    </div>

    <!-- 装饰元素 - 增加页面层次感 -->
    <div class="absolute -top-24 -left-24 w-48 h-48 bg-primary/5 rounded-full blur-3xl"></div>
    <div class="absolute -bottom-32 -right-32 w-64 h-64 bg-secondary/5 rounded-full blur-3xl"></div>
</div>
{% endblock %}

{% block extra_js %}
<script>
document.addEventListener('DOMContentLoaded', () => {
    // 元素获取
    const feedbackForm = document.getElementById('feedbackForm');
    const feedbackResult = document.getElementById('feedbackResult');
    const submitBtn = document.getElementById('submitBtn');
    const countdown提示 = document.getElementById('countdown提示');
    const countdownElement = document.getElementById('countdown');
    const emailInput = document.getElementById('email');
    const contentInput = document.getElementById('content');
    const charCount = document.getElementById('charCount');
    const formGroups = document.querySelectorAll('.form-group');

    // 字符计数功能
    contentInput.addEventListener('input', () => {
        const length = contentInput.value.length;
        charCount.textContent = length;

        // 接近最大长度时的视觉提示
        if (length > 450) {
            charCount.classList.add('text-warning');
        } else {
            charCount.classList.remove('text-warning');
        }

        // 超过最大长度限制
        if (length > 500) {
            contentInput.value = contentInput.value.substring(0, 500);
            charCount.textContent = 500;
            showValidationError(contentInput, '内容不能超过500个字符');
        } else {
            clearValidationError(contentInput);
        }
    });

    // 表单验证 - 实时反馈
    const requiredFields = [emailInput, document.getElementById('subject'), contentInput];
    requiredFields.forEach(field => {
        field.addEventListener('blur', () => {
            if (!field.value.trim()) {
                showValidationError(field, '此字段为必填项');
            } else if (field === emailInput && !isValidEmail(field.value.trim())) {
                showValidationError(field, '请输入有效的邮箱地址');
            } else {
                clearValidationError(field);
                showValidationSuccess(field);
            }
        });

        field.addEventListener('input', () => {
            if (field.value.trim()) {
                clearValidationError(field);
                if (field === emailInput && isValidEmail(field.value.trim())) {
                    showValidationSuccess(field);
                } else if (field !== emailInput) {
                    showValidationSuccess(field);
                }
            }
        });
    });

    // 邮箱验证函数
    function isValidEmail(email) {
        const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    }

    // 显示验证错误
    function showValidationError(field, message) {
        const formGroup = field.closest('.form-group');
        const errorElement = formGroup.querySelector('.error-message');
        const iconElement = formGroup.querySelector('.validation-icon');

        field.classList.remove('border-success', 'focus:border-success');
        field.classList.add('border-danger', 'focus:border-danger');

        if (errorElement) {
            errorElement.textContent = message;
            errorElement.classList.remove('hidden');
            // 错误信息动画
            errorElement.classList.add('animate-pulse');
            setTimeout(() => errorElement.classList.remove('animate-pulse'), 1000);
        }

        if (iconElement) {
            iconElement.classList.remove('hidden', 'text-success');
            iconElement.classList.add('text-danger');
            iconElement.innerHTML = '<i class="fa fa-exclamation-circle"></i>';
        }
    }

    // 清除验证错误
    function clearValidationError(field) {
        const formGroup = field.closest('.form-group');
        const errorElement = formGroup.querySelector('.error-message');
        const iconElement = formGroup.querySelector('.validation-icon');

        field.classList.remove('border-danger', 'focus:border-danger');

        if (errorElement) {
            errorElement.classList.add('hidden');
            errorElement.textContent = '';
        }

        if (iconElement) {
            iconElement.classList.add('hidden');
        }
    }

    // 显示验证成功
    function showValidationSuccess(field) {
        const formGroup = field.closest('.form-group');
        const iconElement = formGroup.querySelector('.validation-icon');

        field.classList.add('border-success');
        field.classList.remove('border-danger', 'focus:border-danger');

        if (iconElement) {
            iconElement.classList.remove('hidden', 'text-danger');
            iconElement.classList.add('text-success');
            iconElement.innerHTML = '<i class="fa fa-check-circle"></i>';
        }
    }

    // 从localStorage获取用户上次提交时间
    const getLastSubmitTime = (email) => {
        const submitRecords = JSON.parse(localStorage.getItem('feedbackSubmitRecords') || '{}');
        return submitRecords[email] || 0;
    };

    // 保存用户提交时间到localStorage
    const saveSubmitTime = (email, timestamp) => {
        const submitRecords = JSON.parse(localStorage.getItem('feedbackSubmitRecords') || '{}');
        submitRecords[email] = timestamp;
        localStorage.setItem('feedbackSubmitRecords', JSON.stringify(submitRecords));
    };

    // 检查并更新按钮状态
    const checkButtonStatus = () => {
        const email = emailInput.value.trim();
        if (!email) return;

        const lastTime = getLastSubmitTime(email);
        const currentTime = Date.now() / 1000; // 转换为秒级时间戳
        const timeDiff = currentTime - lastTime;
        const cooldown = 60; // 10分钟，600秒

        if (lastTime && timeDiff < cooldown) {
            const remainingTime = Math.ceil(cooldown - timeDiff);
            disableSubmitButton(remainingTime);
        } else {
            enableSubmitButton();
        }
    };

    // 禁用提交按钮并显示倒计时
    const disableSubmitButton = (seconds) => {
        submitBtn.disabled = true;
        submitBtn.classList.add('opacity-70', 'cursor-not-allowed', 'bg-gray-400', 'hover:bg-gray-400');
        submitBtn.innerHTML = '<i class="fa fa-clock-o mr-2"></i>请稍后再试';

        // 显示倒计时动画
        countdown提示.classList.remove('hidden');
        setTimeout(() => {
            countdown提示.classList.remove('opacity-0');
        }, 10);

        updateCountdown(seconds);
    };

    // 启用提交按钮
    const enableSubmitButton = () => {
        submitBtn.disabled = false;
        submitBtn.classList.remove('opacity-70', 'cursor-not-allowed', 'bg-gray-400', 'hover:bg-gray-400');
        submitBtn.innerHTML = '<i class="fa fa-paper-plane mr-2"></i>提交反馈';

        // 隐藏倒计时动画
        countdown提示.classList.add('opacity-0');
        setTimeout(() => {
            countdown提示.classList.add('hidden');
        }, 300);
    };

    // 更新倒计时显示
    const updateCountdown = (seconds) => {
        if (seconds <= 0) {
            enableSubmitButton();
            return;
        }

        // 格式化时间为分:秒
        const minutes = Math.floor(seconds / 60);
        const secs = seconds % 60;
        countdownElement.textContent = `${minutes}:${secs < 10 ? '0' + secs : secs}`;

        // 每秒更新一次
        setTimeout(() => {
            updateCountdown(seconds - 1);
        }, 1000);
    };

    // 监听邮箱输入变化，检查提交状态
    emailInput.addEventListener('input', checkButtonStatus);

    // 初始检查按钮状态
    checkButtonStatus();

    // 表单提交处理
    feedbackForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        // 表单验证
        let isValid = true;
        requiredFields.forEach(field => {
            if (!field.value.trim()) {
                showValidationError(field, '此字段为必填项');
                isValid = false;
            } else if (field === emailInput && !isValidEmail(field.value.trim())) {
                showValidationError(field, '请输入有效的邮箱地址');
                isValid = false;
            }
        });

        if (!isValid) {
            // 滚动到第一个错误字段
            const firstError = document.querySelector('.border-danger');
            if (firstError) {
                firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                // 添加抖动动画提示错误
                firstError.classList.add('animate-shake');
                setTimeout(() => firstError.classList.remove('animate-shake'), 500);
            }
            return;
        }

        // 获取表单数据
        const formData = {
            name: document.getElementById('name').value.trim(),
            email: emailInput.value.trim(),
            subject: document.getElementById('subject').value.trim(),
            content: contentInput.value.trim()
        };

        // 前端再次检查提交间隔
        const lastTime = getLastSubmitTime(formData.email);
        const currentTime = Date.now() / 1000;
        if (lastTime && currentTime - lastTime < 60) {
            const remainingTime = Math.ceil(60 - (currentTime - lastTime));
            showFeedbackResult(false, `请勿频繁提交反馈，请${remainingTime}秒后再试`);
            return;
        }

        try {
            // 显示加载状态
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i>提交中...';
            submitBtn.classList.add('opacity-70', 'cursor-wait');

            // 提交反馈
            const response = await fetch('/feedback', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(formData)
            });

            const result = await response.json();

            // 显示结果
            showFeedbackResult(result.success, result.message || result.error);

            // 如果成功提交，保存时间戳并更新状态
            if (result.success && result.timestamp) {
                saveSubmitTime(formData.email, result.timestamp);
                feedbackForm.reset();
                charCount.textContent = '0';
                formGroups.forEach(group => {
                    const input = group.querySelector('input, textarea');
                    const icon = group.querySelector('.validation-icon');
                    const error = group.querySelector('.error-message');

                    if (input) input.classList.remove('border-success');
                    if (icon) icon.classList.add('hidden');
                    if (error) error.classList.add('hidden');
                });
                checkButtonStatus();
            } else {
                // 恢复按钮状态
                submitBtn.disabled = false;
                submitBtn.innerHTML = '<i class="fa fa-paper-plane mr-2"></i>提交反馈';
                submitBtn.classList.remove('opacity-70', 'cursor-wait');
            }

        } catch (error) {
            showFeedbackResult(false, '提交失败，请稍后重试');
            // 恢复按钮状态
            submitBtn.disabled = false;
            submitBtn.innerHTML = '<i class="fa fa-paper-plane mr-2"></i>提交反馈';
            submitBtn.classList.remove('opacity-70', 'cursor-wait');
            console.error('提交反馈出错:', error);
        }
    });

    // 显示反馈结果
    function showFeedbackResult(success, message) {
        feedbackResult.className = success
            ? 'mt-6 p-4 bg-success/10 border border-success/30 rounded-lg text-success shadow-sm'
            : 'mt-6 p-4 bg-danger/10 border border-danger/30 rounded-lg text-danger shadow-sm';

        feedbackResult.innerHTML = `
            <div class="flex items-start">
                <i class="fa ${success ? 'fa-check-circle' : 'fa-exclamation-circle'} mt-0.5 mr-3 text-lg"></i>
                <p>${message}</p>
            </div>
        `;

        // 显示动画
        feedbackResult.classList.remove('hidden', 'opacity-0', 'translate-y-2');

        // 成功提示5秒后自动隐藏
        if (success) {
            setTimeout(() => {
                feedbackResult.classList.add('opacity-0', 'translate-y-2');
                setTimeout(() => {
                    feedbackResult.classList.add('hidden');
                }, 500);
            }, 5000);
        }
    }

    // 添加导航激活状态
    const navLinks = document.querySelectorAll('.nav-link');
    navLinks.forEach(link => {
        if (link.getAttribute('href') === '/feedback') {
            link.classList.add('active');
        } else {
            link.classList.remove('active');
        }
    });
});
</script>

<style>
/* 自定义动画 */
@keyframes pulse-slow {
    0%, 100% { opacity: 1; }
    50% { opacity: 0.7; }
}

@keyframes shake {
    0%, 100% { transform: translateX(0); }
    10%, 30%, 50%, 70%, 90% { transform: translateX(-5px); }
    20%, 40%, 60%, 80% { transform: translateX(5px); }
}

.animate-pulse-slow {
    animation: pulse-slow 3s ease-in-out infinite;
}

.animate-shake {
    animation: shake 0.5s cubic-bezier(.36,.07,.19,.97) both;
}

/* 输入框聚焦效果 */
.input-focus:focus {
    border-color: #3B82F6;
    box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 表单元素过渡效果 */
.form-group label {
    transition: all 0.2s ease;
}

.form-group input:focus + label,
.form-group textarea:focus + label {
    color: #3B82F6;
}
</style>
{% endblock %}